import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useUserStore } from '@/store/user'

// 公共路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    hidden: true
  },
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: ':path(.*)*',
        component: () => import('@/views/redirect/index.vue')
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'Odometer', affix: true }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    hidden: true,
    children: [
      {
        path: 'index',
        name: 'Profile',
        component: () => import('../views/profile/index.vue'),
        meta: { title: '个人中心' }
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: () => import('../views/profile/change-password.vue'),
        meta: { title: '修改密码' }
      }
    ]
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    hidden: true
  }
]

// 动态路由，根据用户权限动态加载
export const asyncRoutes = [
  {
    path: '/system',
    component: Layout,
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'Setting', roles: ['admin', 'manager'] },
    children: [
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/system/user/index.vue'),
        meta: { title: '用户管理', icon: 'User', roles: ['admin', 'manager'] }
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/system/role/index.vue'),
        meta: { title: '角色管理', icon: 'UserFilled', roles: ['admin', 'manager'] }
      },
      {
        path: 'dept',
        name: 'Department',
        component: () => import('@/views/system/dept/index.vue'),
        meta: { title: '部门管理', icon: 'OfficeBuilding', roles: ['admin', 'manager'] }
      },
      {
        path: 'permission',
        name: 'Permission',
        component: () => import('@/views/system/permission/index.vue'),
        meta: { title: '权限管理', icon: 'Lock', roles: ['admin'] }
      }
    ]
  },
  {
    path: '/logs',
    component: Layout,
    redirect: '/logs/request',
    meta: { title: '日志管理', icon: 'Document', roles: ['admin', 'manager'] },
    children: [
      {
        path: 'request',
        name: 'RequestLog',
        component: () => import('@/views/logs/request/index.vue'),
        meta: { title: '请求日志', icon: 'List', roles: ['admin', 'manager'] }
      },
      {
        path: 'login',
        name: 'LoginHistory',
        component: () => import('@/views/logs/login/index.vue'),
        meta: { title: '登录历史', icon: 'Clock', roles: ['admin', 'manager'] }
      }
    ]
  },
  // 404页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404', hidden: true }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫触发:', { to: to.path, from: from.path })
  
  // 获取token
  const userStore = useUserStore()
  const token = userStore.token
  
  console.log('当前token:', token)
  console.log('当前roles:', userStore.roles)
  
  if (token) {
    if (to.path === '/login') {
      // 已登录且要跳转的页面是登录页
      console.log('已登录，重定向到首页')
      next({ path: '/' })
    } else {
      // 判断当前用户是否已拉取完user_info信息
      if (userStore.roles.length === 0) {
        console.log('需要获取用户信息和生成路由')
        try {
          // 获取用户信息
          console.log('开始获取用户信息...')
          await userStore.getInfo()
          console.log('用户信息获取成功:', userStore.roles)
          
          // 根据用户权限生成可访问的路由表
          console.log('开始生成路由...')
          const accessRoutes = await userStore.generateRoutes()
          console.log('路由生成成功:', accessRoutes)
          
          // 动态添加可访问路由表
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          console.log('路由添加完成')
          
          // 设置replace: true，这样导航就不会留下历史记录
          console.log('重新导航到:', to.path)
          next({ ...to, replace: true })
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 移除token并跳转到登录页
          await userStore.logout()
          next(`/login?redirect=${to.path}`)
        }
      } else {
        console.log('用户信息已存在，直接通过')
        next()
      }
    }
  } else {
    // 没有token
    if (to.path === '/login') {
      // 直接进入
      console.log('无token，进入登录页')
      next()
    } else {
      // 否则全部重定向到登录页
      console.log('无token，重定向到登录页')
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router